package com.jiang.vo;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@SuppressWarnings("serial")
public class Account implements Serializable {

	private String name;
	private Integer asset = 0;
	// 定义同步锁
	private ReadWriteLock readwriteLock = new ReentrantReadWriteLock();
	
	public Account() {

	}

	public Account(String name, Integer asset) {
		super();
		this.name = name;
		this.asset = asset;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAsset() {
		return asset;
	}

	public void setAsset(Integer asset) {
		this.asset = asset;
	}

	// 存钱
	public void save(int asset) {
		
		readwriteLock.writeLock().lock(); // 先锁住
		try {
			this.asset+=asset;
			System.out.println("当前线程是:"+Thread.currentThread().getName()+", 写账户名称为:"+this.name+", 账上的钱为:"+this.asset);
			TimeUnit.MILLISECONDS.sleep(500);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			readwriteLock.writeLock().unlock();
		}
	}
	
	/**
	 * 取钱
	 */
	@Override
	public String toString() {
		readwriteLock.readLock().lock();
		try {
			TimeUnit.MILLISECONDS.sleep(1000); //休眠
			return "当前线程是:"+Thread.currentThread().getName()+", 读取的账户名称为:"+this.name+", 账上的钱为:"+this.asset;
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			readwriteLock.readLock().unlock();
		}
	}

}
